/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package cn.lixunims.ims.modular.bill.service.impl;
import java.math.BigDecimal;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.lixunims.ims.modular.basics.entity.ImsCustomer;
import cn.lixunims.ims.modular.basics.entity.ImsProduct;
import cn.lixunims.ims.modular.basics.entity.ImsSupplier;
import cn.lixunims.ims.modular.basics.entity.ImsWarehouse;
import cn.lixunims.ims.modular.basics.service.ImsCustomerService;
import cn.lixunims.ims.modular.basics.service.ImsProductService;
import cn.lixunims.ims.modular.basics.service.ImsSupplierService;
import cn.lixunims.ims.modular.basics.service.ImsWarehouseService;
import cn.lixunims.ims.modular.basics.service.impl.ImsProductServiceImpl;
import cn.lixunims.ims.modular.bill.entity.ImsBillDetail;
import cn.lixunims.ims.modular.bill.param.*;
import cn.lixunims.ims.modular.bill.service.ImsBillDetailService;
import cn.lixunims.ims.modular.inventory.entity.ImsInventoryChangeLog;
import cn.lixunims.ims.modular.inventory.entity.ImsRealTimeInventory;
import cn.lixunims.ims.modular.inventory.service.ImsInventoryChangeLogService;
import cn.lixunims.ims.modular.inventory.service.ImsRealTimeInventoryService;
import cn.lixunims.ims.modular.order.entity.ImsOrderHeader;
import cn.lixunims.ims.modular.order.service.impl.ImsOrderHeaderServiceImpl;
import cn.lixunims.sys.api.SysUserApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.lixunims.common.enums.CommonSortOrderEnum;
import cn.lixunims.common.exception.CommonException;
import cn.lixunims.common.page.CommonPageRequest;
import cn.lixunims.ims.modular.bill.entity.ImsBillHeader;
import cn.lixunims.ims.modular.bill.mapper.ImsBillHeaderMapper;
import cn.lixunims.ims.modular.bill.service.ImsBillHeaderService;

import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 出入库单据头Service接口实现类
 *
 * @author YouDong
 * @date  2024/09/19 14:28
 **/
@Service
public class ImsBillHeaderServiceImpl extends ServiceImpl<ImsBillHeaderMapper, ImsBillHeader> implements ImsBillHeaderService {


    @Autowired
    private ImsSupplierService imsSupplierService;
    @Autowired
    private ImsWarehouseService imsWarehouseService;
    @Autowired
    private ImsCustomerService imsCustomerService;

    @Autowired
    private ImsBillHeaderService imsBillHeaderService;
    @Autowired
    private ImsBillDetailService imsBillDetailService;
    @Autowired
    private ImsRealTimeInventoryService realTimeInventoryService;
    @Autowired
    private ImsProductServiceImpl imsProductServiceImpl;
    @Autowired
    private ImsInventoryChangeLogService imsInventoryChangeLogService;
    @Autowired
    private ImsRealTimeInventoryService imsRealTimeInventoryService;
    @Autowired
    private SysUserApi sysUserApi;
    @Autowired
    private ImsProductService imsProductService;
    @Autowired
    private ImsOrderHeaderServiceImpl imsOrderHeaderServiceImpl;


    @Override
    public Page<ImsBillHeader> page(ImsBillHeaderPageParam imsBillHeaderPageParam) {
        QueryWrapper<ImsBillHeader> queryWrapper = new QueryWrapper<ImsBillHeader>().checkSqlInjection();

        queryWrapper.lambda().like(StrUtil.isNotBlank(imsBillHeaderPageParam.getBillOrderNo()), ImsBillHeader::getBillOrderNo, imsBillHeaderPageParam.getBillOrderNo());

        // 单据类型
        if (StrUtil.isNotBlank(imsBillHeaderPageParam.getBillType())) {
            String billType = imsBillHeaderPageParam.getBillType();
            String[] split = billType.split(",");
            queryWrapper.lambda().in(ImsBillHeader::getBillType, split);
        }


        // 状态
        if (StrUtil.isNotBlank(imsBillHeaderPageParam.getBillStatus())) {
            queryWrapper.lambda().eq(ImsBillHeader::getBillStatus, imsBillHeaderPageParam.getBillStatus());
        } else {
            queryWrapper.lambda().eq(ImsBillHeader::getBillStatus, 1);
        }

        if(ObjectUtil.isAllNotEmpty(imsBillHeaderPageParam.getSortField(), imsBillHeaderPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(imsBillHeaderPageParam.getSortOrder());
            queryWrapper.orderBy(true, imsBillHeaderPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(imsBillHeaderPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(ImsBillHeader::getBillDate);
        }
        Page<ImsBillHeader> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        List<ImsBillHeader> records = page.getRecords();
        if (records.isEmpty()) {
            return page;
        }

        // 客户信息
        List<String> customerIds = CollStreamUtil.toList(records, ImsBillHeader::getCustomerIds);
        List<ImsCustomer> customers;
        if (!customerIds.isEmpty()) {
            customers = imsCustomerService.lambdaQuery().in(ImsCustomer::getCustomerId, customerIds).list();
        } else {
            customers = new ArrayList<>();
        }


        // 关联供应商信息
        List<String> supplierIds = CollStreamUtil.toList(records, ImsBillHeader::getSupplierIds);
        List<ImsSupplier> supplierList;
        if (!supplierIds.isEmpty()) {
            supplierList = imsSupplierService.lambdaQuery().in(ImsSupplier::getSupplierId, supplierIds).list();
        } else {
            supplierList = new ArrayList<>();
        }
        // 业务员
        List<String> userIds = CollStreamUtil.toList(records, ImsBillHeader::getUserIds);
        List<JSONObject> userList = new ArrayList<>();
        if (!userIds.isEmpty()) {
            try {
                userList = sysUserApi.getUserListByIdWithException(userIds);
            } catch (Exception e) {
                // 无业务不处理
                userList = new ArrayList<>();
            }
        }



        // 批量查询关联信息
        List<JSONObject> finalUserList = userList;
        records.forEach(billHeader -> {
            // 关联供应商，客户
            if (!supplierList.isEmpty()) {
                billHeader.setSupplier(supplierList.stream().filter(imsSupplier -> imsSupplier.getSupplierId().equals(billHeader.getSupplierIds())).findFirst().orElse(null));
            }
            if (!customers.isEmpty()) {
                billHeader.setCustomer(customers.stream().filter(imsCustomer -> imsCustomer.getCustomerId().equals(billHeader.getCustomerIds())).findFirst().orElse(null));
            }
            if (!finalUserList.isEmpty()) {
                billHeader.setUser(finalUserList.stream().filter(userObj -> userObj.getStr("id").equals(billHeader.getUserIds())).findFirst().orElse(null));
            }
        });

        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(ImsBillAddParam imsBillAddParam) {
        ImsBillHeader imsBillHeader = BeanUtil.toBean(imsBillAddParam, ImsBillHeader.class);
        this.save(imsBillHeader);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ImsBillHeaderEditParam imsBillHeaderEditParam) {
        ImsBillHeader imsBillHeader = this.queryEntity(imsBillHeaderEditParam.getBillId());
        BeanUtil.copyProperties(imsBillHeaderEditParam, imsBillHeader);
        this.updateById(imsBillHeader);
    }

    @Override
    @Transactional
    public synchronized void delete(ImsBillHeaderIdParam imsBillHeaderIdParam) {
        String billId = imsBillHeaderIdParam.getBillId();

        // 单据修改状态
        ImsBillHeader imsBillHeader = new ImsBillHeader();
        imsBillHeader.setBillId(billId);
        imsBillHeader.setBillStatus("0");
        imsBillHeaderService.updateById(imsBillHeader);
        // 操作库存
        List<ImsRealTimeInventory> resultInventory = new ArrayList<ImsRealTimeInventory>();
        List<ImsInventoryChangeLog> resultLog = new ArrayList<ImsInventoryChangeLog>();

        List<ImsBillDetail> billDetailList = imsBillDetailService.
                lambdaQuery().eq(ImsBillDetail::getBillId, billId).list();

        for (ImsBillDetail imsBillDetail : billDetailList) {
            // 如果出库仓库id存在则添加库存，否则减少库存
            ImsRealTimeInventory inventory = null;
            long currentCount = 0;
            long oldCount = 0;
            if (StrUtil.isNotBlank(imsBillDetail.getRetrievalId())) {
                // 添加库存
                inventory = imsRealTimeInventoryService.lambdaQuery()
                        .eq(ImsRealTimeInventory::getProductId, imsBillDetail.getProductId())
                        .eq(ImsRealTimeInventory::getWareId, imsBillDetail.getRetrievalId()).one();
                Long count = inventory.getCount();
                Long planQuantity = imsBillDetail.getPlanQuantity();
                currentCount = count;
                oldCount = count + planQuantity;
                inventory.setCount(count + planQuantity);

            } else {
                // 减少库存
                inventory = imsRealTimeInventoryService.lambdaQuery()
                        .eq(ImsRealTimeInventory::getProductId, imsBillDetail.getProductId())
                        .eq(ImsRealTimeInventory::getWareId, imsBillDetail.getWarehousingId()).one();
                Long count = inventory.getCount();
                Long planQuantity = imsBillDetail.getPlanQuantity();
                currentCount = count;
                oldCount = count - planQuantity;
                inventory.setCount(count - planQuantity);
            }


            // 记录操作日志
            ImsInventoryChangeLog imsInventoryChangeLog = new ImsInventoryChangeLog();
            imsInventoryChangeLog.setBillId(billId);
            imsInventoryChangeLog.setBillDetailId(imsBillDetail.getSystematicId());
            imsInventoryChangeLog.setProductId(imsBillDetail.getProductId());
            imsInventoryChangeLog.setWareId(imsBillDetail.getWarehousingId()==null ? imsBillDetail.getRetrievalId() : imsBillDetail.getWarehousingId());
            imsInventoryChangeLog.setOperationTime(LocalDate.now());
            imsInventoryChangeLog.setOperationType("删除单据");
            imsInventoryChangeLog.setOldCount(oldCount);
            imsInventoryChangeLog.setActualCount(currentCount);
            imsInventoryChangeLog.setCount(imsBillDetail.getPlanQuantity());
            imsInventoryChangeLog.setMoney(imsBillDetail.getMoney().multiply(BigDecimal.valueOf(imsBillDetail.getPlanQuantity())));
            imsInventoryChangeLog.setUnivalence(imsBillDetail.getUnivalence());


            resultInventory.add(inventory);
            resultLog.add(imsInventoryChangeLog);

        }
        imsRealTimeInventoryService.updateBatchById(resultInventory);
        imsInventoryChangeLogService.saveBatch(resultLog);



    }

    @Override
    public ImsBillAddParam detail(ImsBillHeaderIdParam imsBillHeaderIdParam) {
        ImsBillAddParam result = new ImsBillAddParam();
        ImsBillHeader imsBillHeader = this.queryEntity(imsBillHeaderIdParam.getBillId());
        // 关联供应商或者客户
        if (StrUtil.isNotBlank(imsBillHeader.getSupplierIds())) {
            ImsSupplier supplier = imsSupplierService.queryEntity(imsBillHeader.getSupplierIds());
            imsBillHeader.setSupplier(supplier);
            imsBillHeader.setSupplierName(supplier.getSupplierName());
        }
        if (StrUtil.isNotBlank(imsBillHeader.getCustomerIds())) {
            ImsCustomer imsCustomer = imsCustomerService.queryEntity(imsBillHeader.getCustomerIds());
            imsBillHeader.setCustomer(imsCustomer);
            imsBillHeader.setCustomerName(imsCustomer.getCustomerName());
        }
        // 业务员
        if (StrUtil.isNotBlank(imsBillHeader.getUserIds())) {
            try {
                JSONObject userByIdWithoutException = sysUserApi.getUserByIdWithoutException(imsBillHeader.getUserIds());
                imsBillHeader.setUser(userByIdWithoutException);
                imsBillHeader.setUserName(userByIdWithoutException.getStr("name"));
            } catch (Exception ignored) {
            }
        }
        // 仓库
        if (StrUtil.isNotBlank(imsBillHeader.getWarehousingIds())) {
            ImsWarehouse warehouse = imsWarehouseService.queryEntity(imsBillHeader.getWarehousingIds());
            imsBillHeader.setWarehouse(warehouse);
            imsBillHeader.setWarehouseName(warehouse.getWareName());
        }

        // 清单
        imsBillHeader.setImsBillDetails(imsBillDetailService.list(new LambdaQueryWrapper<ImsBillDetail>().eq(ImsBillDetail::getBillId, imsBillHeader.getBillId())));


        List<ImsBillDetail> list = imsBillDetailService.lambdaQuery().eq(ImsBillDetail::getBillId, imsBillHeader.getBillId()).list();
        // 商品名称
        for (ImsBillDetail imsBillDetail : list) {
            ImsProduct imsProduct = imsProductService.queryEntity(imsBillDetail.getProductId());
            if (imsProduct != null) {
                imsBillDetail.setProductTotalName(imsProduct.getProductCode() + "-"+imsProduct.getProductName());
            }
            if (StrUtil.isNotBlank(imsBillDetail.getRetrievalId())) {
                ImsWarehouse byId = imsWarehouseService.getById(imsBillDetail.getRetrievalId());
                imsBillDetail.setWareName(byId.getWareName());
            } else if (StrUtil.isNotBlank(imsBillDetail.getWarehousingId())){
                ImsWarehouse byId = imsWarehouseService.getById(imsBillDetail.getWarehousingId());
                imsBillDetail.setWareName(byId.getWareName());
            }
        }


        result.setHeader(imsBillHeader);
        result.setRecordList(list);

        return result;
    }

    @Override
    public ImsBillHeader queryEntity(String id) {
        ImsBillHeader imsBillHeader = this.getById(id);
        if(ObjectUtil.isEmpty(imsBillHeader)) {
            throw new CommonException("出入库单据头不存在，id值为：{}", id);
        }
        return imsBillHeader;
    }

    /**
     * 入库
     *
     * @param imsBillAddParam
     */
    @Override
    @Transactional
    public synchronized void inWare(ImsBillAddParam imsBillAddParam) {
        ImsBillHeader billHeader = imsBillAddParam.getHeader();
        List<ImsBillDetail> imsBillDetails = imsBillAddParam.getRecordList();
        // 不保存id，自动生成
        billHeader.setBillId(null);
        // TODO 单据状态
        billHeader.setBillStatus("1");
        imsBillHeaderService.save(billHeader);


        // 手动插入主键
        imsBillDetails.forEach(imsBillDetail -> {
            imsBillDetail.setSystematicId(null);
            imsBillDetail.setBillId(billHeader.getBillId());
        });

        // 单据和单据明细保存
        imsBillDetailService.saveBatch(imsBillDetails);


        // 处理实时库存
        List<ImsInventoryChangeLog> inventoryLogBatch = new ArrayList<>();

        imsBillDetails.forEach(imsBillDetail -> {
            String systematicId = imsBillDetail.getSystematicId();
            String productId = imsBillDetail.getProductId();
            String measureUnit = imsBillDetail.getMeasureUnit();
            String retrievalId = imsBillDetail.getRetrievalId();
            Long actualCount = imsBillDetail.getPlanQuantity();
            BigDecimal univalence = imsBillDetail.getUnivalence();
            String warehousingId = imsBillDetail.getWarehousingId();

            // 库存变动日志
            ImsInventoryChangeLog imsInventoryChangeLog = new ImsInventoryChangeLog();


            // 实时库存处理
            // 尝试获取当前库存，没有则创建，有则修改库存
            ImsRealTimeInventory currentInventory = imsRealTimeInventoryService.lambdaQuery()
                    .eq(ImsRealTimeInventory::getProductId, productId)
                    .eq(ImsRealTimeInventory::getWareId, StrUtil.isBlank(warehousingId) ? retrievalId : warehousingId ).one();
            if (currentInventory == null) {
                currentInventory = new ImsRealTimeInventory();
                currentInventory.setProductId(productId);
                currentInventory.setWareId(StrUtil.isBlank(warehousingId) ? retrievalId : warehousingId);
                currentInventory.setCount(0L);
                currentInventory.setCost(BigDecimal.ZERO);
                currentInventory.setUnitId(measureUnit);
                currentInventory.setSupplierId(billHeader.getSupplierIds());
                currentInventory.setStatus("ENABLE");
                // 实时库存没有这个仓库下的商品，当前无库存数
                imsInventoryChangeLog.setOldCount(0L);
                inOutWare(billHeader, imsBillDetail, currentInventory, actualCount, univalence);
                imsRealTimeInventoryService.save(currentInventory);
            } else {
                // 实时库存存在这个仓库下的商品，当前库存数为没有变动的实时库存的库存数
                imsInventoryChangeLog.setOldCount(currentInventory.getCount());
                // 出入库计算逻辑
                inOutWare(billHeader, imsBillDetail, currentInventory, actualCount, univalence);
                imsRealTimeInventoryService.updateById(currentInventory);
            }

            // 库存变动日志
            imsInventoryChangeLog.setId(IdWorker.getIdStr());
            imsInventoryChangeLog.setBillDetailId(systematicId);
            imsInventoryChangeLog.setProductId(productId);
            imsInventoryChangeLog.setBillId(billHeader.getBillId());
            imsInventoryChangeLog.setOperationType(billHeader.getBillType());
            imsInventoryChangeLog.setOperationTime(billHeader.getBillDate());
            imsInventoryChangeLog.setActualCount(currentInventory.getCount());
            imsInventoryChangeLog.setCount(actualCount);
            imsInventoryChangeLog.setMoney(univalence.multiply(new BigDecimal(actualCount)));
            imsInventoryChangeLog.setUnivalence(univalence);
            imsInventoryChangeLog.setWareId(StrUtil.isBlank(warehousingId) ? retrievalId : warehousingId);


            inventoryLogBatch.add(imsInventoryChangeLog);
        });

        // 批量保存库存和日志
        imsInventoryChangeLogService.saveBatch(inventoryLogBatch);
    }

    /**
     * 出入库计算逻辑
     * @author YouDong
     * @date 2024/10/21
     */
    private static void inOutWare(ImsBillHeader billHeader, ImsBillDetail imsBillDetail, ImsRealTimeInventory currentInventory, Long actualCount, BigDecimal univalence) {
        // 判断类型，销售出库，采购入库
        switch (billHeader.getBillType()) {
            case "销售出库":
            case "盘亏出库":
                /* 出库逻辑 */

                // 计算出库后的库存数量
                long newCount = currentInventory.getCount() - actualCount;
                if (newCount < 0) {
                    throw new IllegalArgumentException("库存不足，无法出库");
                }
                currentInventory.setCount(newCount);
                break;

            case "退货入库":
            case "盘盈入库":
            case "采购入库":
                /* 入库逻辑 */

                // 计算新的库存数量
                long updatedCount = currentInventory.getCount() + actualCount; // 当前库存 + 新入库数量

                // 计算当前库存的总成本
                BigDecimal currentTotalCost = currentInventory.getCost().multiply(new BigDecimal(currentInventory.getCount()));

                // 计算新入库的总成本
                BigDecimal newTotalCost = imsBillDetail.getUnivalence().multiply(new BigDecimal(actualCount));

                // 合并总成本
                BigDecimal totalCost = currentTotalCost.add(newTotalCost);

                // 更新平均成本
                BigDecimal updatedCost;
                if (updatedCount > 0) {
                    updatedCost = totalCost.divide(new BigDecimal(updatedCount), 2, RoundingMode.HALF_UP); // 使用新的库存数量来计算平均成本
                } else {
                    updatedCost = BigDecimal.ZERO;
                }

                // 更新库存信息
                currentInventory.setCount(updatedCount);
                currentInventory.setCost(updatedCost);
                break;
        }
    }


    /**
     * 出库
     *
     * @param imsBillAddParam
     */
    @Override
    @Transactional
    public void outWare(ImsBillAddParam imsBillAddParam) {
        inWare(imsBillAddParam);
    }

    @Override
    public String getBillNo(String billType) {
        // 生成规则 类型+日期+流水号
        String enBillType = "";
        switch (billType) {
            case "销售出库":
                enBillType = "XXCK";
                break;
            case "盘亏出库":
                enBillType = "FCCK";
                break;

            case "采购入库":
                enBillType = "CGRK";
                break;
            case "盘盈入库":
                enBillType = "CXCK";
                break;
        }

        return enBillType + "-" + DateUtil.format(new Date(), "yyyyMMdd") + "-"   +(imsBillHeaderService.lambdaQuery().eq(ImsBillHeader::getBillType, billType).count()+1);
    }

    /**
     * 获取全部单据
     *
     * @param imsAllBillParam
     * @author YouDong
     * @date 2024/10/23
     */
    @Override
    public List<ImsBillHeader> getAllBill(ImsAllBillParam imsAllBillParam) {
        LambdaQueryChainWrapper<ImsBillHeader> billQuery = this.lambdaQuery();
        LambdaQueryChainWrapper<ImsOrderHeader> orderQuery = imsOrderHeaderServiceImpl.lambdaQuery();

        if (StrUtil.isNotBlank(imsAllBillParam.getBillOrderNo())) {
            billQuery.like(ImsBillHeader::getBillOrderNo, imsAllBillParam.getBillOrderNo());
            orderQuery.like(ImsOrderHeader::getBillOrderNo, imsAllBillParam.getBillOrderNo());
        }
        if (StrUtil.isNotBlank(imsAllBillParam.getBillType())) {
            billQuery.eq(ImsBillHeader::getBillType, imsAllBillParam.getBillType());
            orderQuery.eq(ImsOrderHeader::getBillType, imsAllBillParam.getBillType());
        }
        if (imsAllBillParam.getBillDate() != null && !imsAllBillParam.getBillDate().isEmpty()) {
            billQuery.between(ImsBillHeader::getBillDate, imsAllBillParam.getBillDate().get(0), imsAllBillParam.getBillDate().get(1));
            orderQuery.between(ImsOrderHeader::getBillDate, imsAllBillParam.getBillDate().get(0), imsAllBillParam.getBillDate().get(1));
        }

        // 状态
        if (StrUtil.isNotBlank(imsAllBillParam.getBillStatus())) {
            billQuery.eq(ImsBillHeader::getBillStatus, imsAllBillParam.getBillStatus());
            orderQuery.eq(ImsOrderHeader::getBillStatus, imsAllBillParam.getBillStatus());
        } else {
            billQuery.eq(ImsBillHeader::getBillStatus, 1);
            orderQuery.eq(ImsOrderHeader::getBillStatus, 1);
        }

        List<ImsBillHeader> result = billQuery.list();
        List<ImsOrderHeader> list = orderQuery.list();
        for (ImsOrderHeader imsOrderHeader : list) {
            ImsBillHeader imsBillHeader = new ImsBillHeader();
            BeanUtil.copyProperties(imsOrderHeader, imsBillHeader);
            imsBillHeader.setByOrder("order");
            result.add(imsBillHeader);
        }
        // 根据创建时间倒叙排序
        result.stream().sorted(Comparator.comparing(ImsBillHeader::getCreateTime).reversed()).collect(Collectors.toList());

        return result;
    }
}
